package com.mcb_wxc.util;

import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.*;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @描述: 阿里云开放式存储（OSS）工具类
 * @版本: V1.0
 * https://img.xfj100.com/
 */
public class AliyunOSSUtil {
	// 变量 accessKeyId 与 accessKeySecret 是由系统分配给用户的，称为ID对，用于标识用户，为访问OSS做签名验证
	private static final String accessKeyId = "AvJlQM9hDA0XCjle";
	private static final String accessKeySecret = "4qqRZfxkPbOY4naXoxij4AngJTmkpz";
	// Bucket是OSS上的命名空间，相当于数据的容器，可以存储若干数据实体（Object）
	private static final String bucketName = "xfj-image";
	// 初始化一个OSSClient
	private static final OSSClient client = new OSSClient(accessKeyId, accessKeySecret);

	/**
	 * 单个文件上传到阿里云
	 * @param key 是文件的名字，也是存在数据库的地址    例：uploads/2014/0630/0bed845745a92e995eb28e30ee56a43f.png
	 * @param filePath 是文件本地路径    例：D:/uploads/2014/0630/0bed845745a92e995eb28e30ee56a43f.png
	 * @return String 文件的MD5值
	 * @throws FileNotFoundException
	 */
	public static String putObject(String key, String filePath) throws Exception {

		// 获取指定文件的输入流
		File file = new File(filePath);
		InputStream content = new FileInputStream(file);

		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();

		// 必须设置ContentLength
		meta.setContentLength(file.length());

		// 上传Object.
		PutObjectResult result = client.putObject(bucketName, key, content, meta);

		//删除本地文件
		
		// Put Object请求处理成功后，OSS会将收到文件的MD5值放在返回结果的ETag中。用户可以根据ETag检验上传的文件与本地的是否一致
		return result.getETag();
	}
	
	public static String putObject(String key, MultipartFile file) throws Exception {
		
		InputStream content = file.getInputStream();
		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();

		// 必须设置ContentLength
		meta.setContentLength(file.getSize());

		// 上传Object.
		PutObjectResult result = client.putObject(bucketName, key, content, meta);

		//删除本地文件
		
		// Put Object请求处理成功后，OSS会将收到文件的MD5值放在返回结果的ETag中。用户可以根据ETag检验上传的文件与本地的是否一致
		return result.getETag();
	}
	
	public static String putObject(String key, InputStream file) throws Exception {
		
		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();

		// 必须设置ContentLength
		meta.setContentLength(file.available());

		// 上传Object.
		PutObjectResult result = client.putObject(bucketName, key, file, meta);

		//删除本地文件
		
		// Put Object请求处理成功后，OSS会将收到文件的MD5值放在返回结果的ETag中。用户可以根据ETag检验上传的文件与本地的是否一致
		return result.getETag();
	}
	
	
	/**
	 * 列出所有Object
	 */
	public static void listObjects() {

		// 获取指定bucket下的所有Object信息
        ObjectListing listing = client.listObjects(bucketName);

        // 遍历所有Object 最多返回100个Object
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }
	}
	
	/**
	 * 获取指定Object 
	 * 记得在用完之后关闭这个流
	 * @param key
	 * @return InputStream
	 * @throws IOException
	 */
	public static InputStream getObject(String key) throws IOException {

	    // 获取Object，返回结果为OSSObject对象
	    OSSObject object = client.getObject(bucketName, key);

	    // 获取Object的输入流
	    InputStream objectContent = object.getObjectContent();

	    return objectContent;
	}

	/**
	 * 上传网络图片
	 * @param imgUrl 网络文件url
	 * @param fileName 自定义文件名
	 * @return
	 */
	public static String uploadNetworkPictures(String imgUrl,String fileName) {
		String files = "";
		URL url;
		InputStream inStream = null;
		try {
			imgUrl = imgUrl;
			url = new URL(imgUrl);
			// 打开链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方式为"GET"
			conn.setRequestMethod("GET");
			// 超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			inStream = conn.getInputStream();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM/dd");
			//File pdfFile = new File(url);
			//FileInputStream fileInputStream = new FileInputStream(pdfFile);
			MultipartFile file = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), inStream);
			if(file != null){
				String path = "upload/images/" + sdf.format(new Date()) + "/" + file.getOriginalFilename();
				AliyunOSSUtil.putObject(path, file);
				if(files.equals("")) {
					files += path;
				} else {
					files += "," + path;
				}
			}
			//System.out.print("图片路径----------"+ files);
		} catch(Exception e) {
			System.out.print("上传图片失败！"+e.getMessage());
		} finally {
			try {
				//关闭输入流
				inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return files;
	}


	public static void main(String[] args) {
		//String resultUrl = AliyunOSSUtil.uploadNetworkPictures("http://image.xfj100.com/uploads/2019/0220/f7a2b6d5-5673-4662-96d3-5c63477625d0.jpg@30w_100Q_4x.jpg", "default"+".jpg");



		String imgUrl = "http://qr.liantu.com/api.php?text="+"I WANT TRY";
		String resultUrl = AliyunOSSUtil.uploadNetworkPictures(imgUrl, "ILoveTry.jpg");
		System.out.println(resultUrl);
	}
}
